//
//  NewTweetDialog.m
//  trowel
//
//  Created by Jonathan Reams on 1/20/10.
//  Copyright 2010 ReamsTronics. All rights reserved.
//

#import "NewTweetDialog.h"
#import "JSON/SBJSON.h"

@implementation NewTweetDialog

- (IBAction) doTweet: (id) sender {
	[tweetProgress startAnimation:self];
	NSString * tweetString = [[tweetText stringValue] stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding];
	BOOL useSSL = [[config getUserSetting:@"usessl" forUser:[accountToUse objectValueOfSelectedItem]] boolValue];
	NSMutableString * urlString = [NSMutableString stringWithFormat:@"http%@://twitter.com/statuses/update.json?status=%@", 
								   useSSL ? @"s" : @"", tweetString];
	if(replyId > 0)
		[urlString appendFormat:@"&in_reploy_to_status_id=%qui", replyId];
	NSError * error;
	NSString * jsonData = [config stringWithURL:[NSURL URLWithString:urlString] 
										forUser:[accountToUse objectValueOfSelectedItem] 
										  error:&error
									  forMethod:@"POST"];
	
	if(jsonData == nil)
	{
		[tweetProgress stopAnimation:self];
		NSAlert * errorMsg = [NSAlert alertWithError:error];
		[errorMsg runModal];
		return;
	}
	NSMutableDictionary * dictionary = [[[SBJsonParser alloc] init] objectWithString: jsonData];
	if(dictionary != nil)
	{
		[tweetProgress stopAnimation:self];
		if([dictionary objectForKey:@"error"] != nil)
			NSRunAlertPanel(@"Twitter Error!", [dictionary objectForKey:@"error"], @"OK", NULL, NULL);
	}
	[window orderOut:self];
	replyId = 0;
	replyUsername = [NSString string];
}

- (IBAction) shortenURLs: (id) sender {
	[tweetProgress startAnimation:self];
	NSMutableString * textValue = [NSMutableString stringWithString:[tweetText stringValue]];
	NSScanner * scanner = [NSScanner scannerWithString:textValue];
	while(![scanner isAtEnd])
	{
		NSUInteger start, end;
		[scanner scanUpToString:@"http://" intoString:NULL];
		start = [scanner scanLocation];
		[scanner scanUpToString:@" " intoString:NULL];
		end = [scanner scanLocation];
		if(end - start <= 18)
			continue;
		NSStringEncoding encoding;
		NSError * anyError = nil;
		NSString * requestURL = [NSString stringWithFormat:@"http://is.gd/api.php?longurl=%@",
								 [textValue substringWithRange:(NSRange){start, end - start}]];
		NSString * shortenedURL = [NSString stringWithContentsOfURL: [NSURL URLWithString: requestURL] 
													   usedEncoding: &encoding 
															  error: &anyError]; 
		[textValue replaceCharactersInRange:(NSRange){start, end - start} withString:shortenedURL];
	}
	[tweetText setStringValue:textValue];
	[tweetProgress stopAnimation:self];
}

- (void) controlTextDidChange: (NSNotification *)aNotification {
	[remainingCharactersField setStringValue:[NSString stringWithFormat:@"Remaining Characters: %i", 140 - [[tweetText stringValue] length]]];
}

- (void) setReply: (NSNumber*) idnum toUser: (NSString*) username {
	replyId = [idnum unsignedLongLongValue];
	replyUsername = username;
	NSString * newTweetText = [NSString stringWithFormat:@"@%@ ", username];
	[tweetText setStringValue:newTweetText];
	[self controlTextDidChange:nil];
}

- (void) setConfig: (Configuration*) newConfig {
	config = newConfig;
	[accountToUse removeAllItems];
	[accountToUse addItemsWithObjectValues:[config getUsers]];
	[accountToUse selectItemWithObjectValue:[config getGlobalSetting:@"defaultUser"]];
}

- (IBAction) doNewTweet: (id) sender {
	[tweetText setStringValue:@""];
	if(![[accountToUse objectValues] isEqualToArray:[config getUsers]])
		[self setConfig: config];
	if(![window isVisible])
	{
		[NSApp activateIgnoringOtherApps:YES];
		[window makeKeyAndOrderFront:sender];
	}
	[tweetText setStringValue:@""];
	[self controlTextDidChange:nil];
}

@end
